package com.ng.framework.view.desktop;

import java.awt.Container;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;

import com.ng.framework.persistence.NGGenericPersistence;
import com.ng.framework.view.desktop.filters.NGFilter;
import com.ng.framework.view.desktop.filters.NGFiltersPanel;

public abstract class NGEntitySelectorDialog<T, P extends NGGenericPersistence<T>> extends JDialog implements ActionListener {

	private static final long serialVersionUID = -8380688002830536473L;

	private P persistence;

	private NGFiltersPanel<T, P> ngFiltersPanel;
	private NGTablePanel<T, P> table;
	private JButton buttonVolver;

	private NGEntitySelectorField<T, P> ngEntitySelectorField;

	public NGEntitySelectorDialog(final Frame owner, NGEntitySelectorField<T, P> ngEntitySelectorField) {
		super(owner, true);
		this.ngEntitySelectorField = ngEntitySelectorField;

		this.persistence = this.createPersistence();
		this.initComponents();
		this.buildGui();
		this.populateTable(persistence.getAll());

	}

	protected abstract P createPersistence();

	private void initComponents() {
		this.table = this.createTable(persistence, ngEntitySelectorField);
		this.ngFiltersPanel = new NGFiltersPanel(this.createFilters(), table, persistence);
		this.buttonVolver = NGGUIUtils.createTextButton("Volver", this);
	}

	protected abstract List<NGFilter> createFilters();

	protected abstract NGTablePanel<T, P> createTable(P persistence, NGEntitySelectorField<T,P> ngEntitySelectorField);

	private void buildGui() {
		Container contentPane = this.getContentPane();

		contentPane.setLayout(new GridBagLayout());

		contentPane.add(ngFiltersPanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.CENTER,
				GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		contentPane.add(table, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				new Insets(0, 5, 5, 5), 0, 0));
		contentPane.add(buttonVolver, new GridBagConstraints(0, 2, 1, 1, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
				new Insets(0, 5, 5, 5), 0, 0));
	}

	private void populateTable(List<T> data) {
		this.table.setData(data);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == buttonVolver) {
			this.dispose();
		}
	}

}
